#!/usr/bin/env bash
#
# Summary: A package manager for shell scripts
#
# Usage: basher <command> [<args>]

resolve_link() {
  $(type -p greadlink readlink | head -1) "$1"
}

abs_dirname() {
  local cwd="$(pwd)"
  local path="$1"

  while [ -n "$path" ]; do
    cd "${path%/*}"
    local name="${path##*/}"
    path="$(resolve_link "$name" || true)"
  done

  pwd
  cd "$cwd"
}

if [ -z "$BASHER_ROOT" ]; then
  BASHER_ROOT="$HOME/.basher"
fi
export BASHER_ROOT

if [ -z "$BASHER_PREFIX" ]; then
  BASHER_PREFIX="$BASHER_ROOT/cellar"
fi
export BASHER_PREFIX

if [ -z "$BASHER_PACKAGES_PATH" ]; then
  BASHER_PACKAGES_PATH="$BASHER_PREFIX/packages"
fi
export BASHER_PACKAGES_PATH

if [ -z "$BASHER_INSTALL_BIN" ]; then
  BASHER_INSTALL_BIN="$BASHER_PREFIX/bin"
fi
export BASHER_INSTALL_BIN

if [ -z "$BASHER_INSTALL_MAN" ]; then
  BASHER_INSTALL_MAN="$BASHER_PREFIX/man"
fi
export BASHER_INSTALL_MAN

bin_path="$(abs_dirname "$0")"
export PATH="${bin_path}:${PATH}"

command="$1"
case "$command" in
"")
  basher-help
  ;;
* )
  command_path="$(command -v "basher-$command" || true)"
  if [ -z "$command_path" ]; then
    echo "basher: no such command '$command'" >&2
    exit 1
  fi

  shift 1
  exec "$command_path" "$@"
  ;;
esac
